package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.UserLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(version = "1.0.0")
public class UserLogApiImpl implements UserLogApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Map<String,Object> queryUserLogs(Integer uid, Integer page, Integer pagesize, String sortProp, String sortOrder) {
        Query queryCount = Query.query(Criteria.where("userId").is(uid).and("type").is(1));
        int count = (int) mongoTemplate.count(queryCount, "user_log_20210718");
        System.out.println(count);
        Pageable pageable = PageRequest.of(page-1,pagesize);
        Query query = null;
        if (sortOrder.equals("ascending")){
            query = Query.query(Criteria.where("userId").is(uid).and("type").is(1)).with(Sort.by(Sort.Order.asc("loginDate"))).with(pageable);
        }else {
            query = Query.query(Criteria.where("userId").is(uid).and("type").is(1)).with(Sort.by(Sort.Order.desc("loginDate"))).with(pageable);
        }
        List<UserLog> userLogList = mongoTemplate.find(query, UserLog.class,"user_log_20210718");
        Map<String,Object> map = new HashMap<>();
        map.put("count",count);
        map.put("userLogList",userLogList);
        return map;
    }
}
